import { Injectable } from '@angular/core';
import { UserAuthService } from '@core/services/user-auth.service';
import { UserInfoModel } from '../../domain/user-info-model';
import { ApiService } from '@core/services/http/api.service';
import {map, mergeMap} from "rxjs/operators";
import {Observable} from "rxjs";

@Injectable()
export class AnalysisService {
  public userKey = 'userCompany';
  private userInfo = this.userAuthService.getUserInfoObj();
  public storage: Storage = sessionStorage;
  private pt_company: any[];

  constructor(private userAuthService: UserAuthService,
              private apiService: ApiService) {
 }

  /** 获取local里面posts数据 **/
  public getCompany() {
    // if (this.userInfo) {
    //   const postsData = this.userInfo.userAccount.posts.map(item => {
    //     const postId = this.userInfo.userAccount.post.company.id;
    //     if (postId === item.company.id) {
    //       return { name: item.company.name, id: item.company.id, checked: true };
    //     } else {
    //       return { name: item.company.name, id: item.company.id, checked: false };
    //     }
    //   });
    //   return this.unique(postsData);
    // }
  }

  /** 获取公司logo **/
  public getImges(img: any) {
    return new Promise(resolve => {
      this.apiService.post('cm.company.getImage', {'body': JSON.stringify({ imageName: img })}).subscribe((body) => {
        // if (body) {
          resolve(body);
        // }
      })
    })
  }

  /** 数组去重 **/
  public unique(array: any[]) {
    let temp = [array[0]];
    if (typeof(array[0]) === 'object') {
      for (let i = 1; i < array.length; i++) {
        if (array[i].id !== temp[temp.length - 1].id) {
          temp.push(array[i]);
        }
      }
    } else {
      for (let i = 1; i < array.length; i++) {
        if (array[i] !== temp[temp.length - 1]) {
          temp.push(array[i]);
        }
      }
    }

    return temp;
  };

  /** 数组去空字符 **/
  public remove(arr: any[]) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i] == '' || arr[i] == null || typeof(arr[i]) == undefined) {
        arr.splice(i, 1);
        i = i - 1;
      }
    }
    return arr;
  }

  /**
   * 存储用户信息
   */
  public storeLocal(userInfo: string) {
    this.storage.setItem(this.userKey, userInfo);
  }

  /** 移除用户信息 **/
  public removeCompany() {
    this.storage.removeItem(this.userKey);
  }

  /**
   *获取存储在 localStorage 中的用户信息
   * @returns {UserInfoModel}
   */
  public getLocalObj(): UserInfoModel {
    try {
      const userInfo = this.storage.getItem(this.userKey);
      const userInfoObj = JSON.parse(userInfo);
      return !!userInfoObj ? userInfoObj : null;
    } catch (e) {
      return null;
    }
  }

  /**  调用获取公司
   *  通过post.localPermit.permitPurposeSearch.pt_company获取公司
   * **/
  public getLocalPermit(permitId: any) {
    this.apiService.post('cm.company.findAllCompany', {}).pipe(
      map((body) => {
        this.pt_company=body['pt_company'];
        return body['pt_company'];
      }),
      mergeMap(data => this.getForUi(data,permitId)),
    ).subscribe();

  }

  public getLocalPermitA(permitId: any): Observable<any> {
    // this.getLocalPermitAll().then(value =>  { this.pt_company = value['pt_company'] });
    // this.
    return this.apiService.post('cm.company.findAllCompany', {}).pipe(
      map((body) => {
        this.pt_company=body['pt_company'];
        return body['pt_company'];
      }),
      mergeMap(data => this.getForUi(data,permitId)),
    );

  }

  private getForUi(companyId,permitId): Observable<any> {
    return this.apiService.post('aut.localPermit.findOneForUi', { 'body': JSON.stringify({ id: permitId }) }).pipe(
         map(body=> {
           if (body) {
             const userInfo = this.userAuthService.getUserInfoObj();
             let localPermit: any[];
             if (JSON.stringify(body.permitPurposeSearch.pt_company) === '[]') {
               localPermit = companyId;
             } else {
               localPermit = body.permitPurposeSearch.pt_company;
             }
             userInfo.userAccount['localPermit'] = localPermit;
             this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
             const companyClone = [{}, {}, {}];
             const direct: any[] = [];
             const partner: any[] = [];
             const join: any[] = [];
             const postsData = localPermit.map(item => {
               return {...item, checked: true};
             });
             for (const item of postsData) {
               if (item.operation === '直营') {
                 direct.push(item);
               } else if (item.operation === '合伙人') {
                 partner.push(item);
               } else if (item.operation === '赋能店') {
                 join.push(item);
               }
             }
             companyClone[0] = {array: direct, status: 'selectall', disable: 'none'};
             companyClone[1] = {array: partner, status: 'selectall', disable: 'none'};
             companyClone[2] = {array: join, status: 'selectall', disable: 'none'};
             for (let i = 0, len = companyClone.length; i < len; i++) {
               if (companyClone[i]['array'].length > 0) {
                 companyClone[i]['array'] = this.unique(companyClone[i]['array']);
               }
             }
             this.storeLocal(JSON.stringify(companyClone));

           }
           return {};
         }
      ));
  }

}
